package org.example.advice;

import org.example.constant.BaseErrorCode;
import org.example.util.JsonUtil;
import org.example.vo.GenericResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Locale;

/**
 * @author zw531
 * @date 2021/7/8 10:10 am
 */
@RestControllerAdvice
public class ResponseFormatter implements ResponseBodyAdvice<Object> {
    @Autowired
    private MessageSource messageSource;
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        GenericResponse gr = new GenericResponse();
        gr.setCode(BaseErrorCode.INVOKE_SUCCESS.code);
        gr.setMessage(messageSource.getMessage(BaseErrorCode.INVOKE_SUCCESS.message, null, Locale.CHINA));
        gr.setData(body);
        // 对String类型的返回需要特殊处理
        if (body instanceof String) {
            return JsonUtil.toJson(gr);
        }
        // 对已包装过的异常类型直接返回
        if (body instanceof GenericResponse) {
            return body;
        }

        return gr;
    }
}
